﻿using Framework;
using System;
using System.Linq;
using System.Windows.Forms;

namespace Shell.Controllers
{
    internal class TabController : ITabController
    {
        #region Implementation of ITabController

        public void OpenTab(TabPage tabPage, bool isClose = true)
        {
            var tabControl = MainForm.TabControl;
            if (tabPage == null)
                return;

            var tab =
                tabControl.TabPages.OfType<TabPage>().FirstOrDefault(model => string.Equals(model.Text, tabPage.Text));
            if (tab != null)
            {
                tabControl.SelectTab(tab.TabIndex);
                return;
            }

            foreach (Control control in tabPage.Controls)
                control.Dock = DockStyle.Fill;
            tabPage.AutoScroll = true;
            tabPage.Tag = isClose;
            tabControl.TabPages.Add(tabPage);
            tabControl.SelectTab(tabPage);
            var c = tabPage.Controls.OfType<Control>().FirstOrDefault();
            if (c != null)
            {
                c.Focus();
            }
        }

        public void OpenTab(string title, Action<TabPage> action, bool isClose = true)
        {
            var tabControl = MainForm.TabControl;
            if (action == null)
                return;
            var tab =
                tabControl.TabPages.OfType<TabPage>().FirstOrDefault(model => string.Equals(model.Text, title));
            if (tab != null)
            {
                tabControl.SelectTab(tab.TabIndex);
                return;
            }
            var tabPage = new TabPage(title);
            action(tabPage);
            OpenTab(tabPage, isClose);
        }

        #endregion Implementation of ITabController
    }
}